package cn.cew.bytespyserver.exeception;

import cn.cew.bytespyserver.page.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @author chenenwei
 * @version 1.0.0
 * @description TODO
 * @createTime 2022-10-15 19:48:00
 */
@Slf4j
@RestControllerAdvice
public class GlobalHandler {

    @ExceptionHandler(value = Exception.class)
    public ApiResponse handle (Exception e) {
        log.error("【服务异常】", e);
        return ApiResponse.error(e.getMessage());
    }

    /**
     * 处理validate的校验异常
     */
    @ExceptionHandler(BindException.class)
    public ApiResponse handleBindException(BindException e) {
        return ApiResponse.error(e.getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * 处理RequestBody validate的校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return ApiResponse.error(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * 处理参数列表字段validate的校验异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ApiResponse handleConstraintViolationException(ConstraintViolationException e) {
        return ApiResponse.error(e.getMessage());
    }

}
